package Pet.Management.controller;

import Pet.Management.domain.dto.PostDTO;
import Pet.Management.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/post")
public class PostController {

    @Autowired
    private PostService postService;

    /**
     * 获取帖子列表
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getPostList(
            @RequestParam(required = false) String title,
            @RequestParam(required = false) String author,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {

        // 创建分页对象（注意：pageNum需要减1，因为Spring Data JPA的页码从0开始）
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        
        // 获取分页数据
        Page<PostDTO> page = postService.getPostList(title, author, pageRequest);
        
        Map<String, Object> response = new HashMap<>();
        response.put("total", page.getTotalElements());
        response.put("rows", page.getContent());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/{postId}")
    public ResponseEntity<Map<String, Object>> deletePost(@PathVariable Long postId) {
        boolean result = postService.deletePost(postId);
        
        Map<String, Object> response = new HashMap<>();
        if (result) {
            response.put("code", 200);
            response.put("msg", "删除成功");
        } else {
            response.put("code", 500);
            response.put("msg", "删除失败");
        }
        
        return ResponseEntity.ok(response);
    }
} 